<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { studentshowListService, studentAddService, studentUpdateService, studentDeleteService, studentshowbyidListService, studentshowbynameListService } from '@/api/Student.js'
import request from '@/utils/request.js'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'

// 将 students 初始化为空数组
const students = ref([])
// 存储输入的学生 ID
const searchStudentId = ref('')
// 存储输入的搜索关键词
const searchKeyword = ref('')
//声明异步函数，查询所有学生信息
const studentList = async()=>{
    let result = await studentshowListService();
    students.value = result.data;
}
// 页面加载时查询所有学生信息
studentList();

// 声明异步函数，根据学生 ID 查询学生信息
const searchStudentById = async() => {
    if (!searchKeyword.value) {
        ElMessage.warning('请输入学生 ID');
        return;
    }
    
    const result = await studentshowbyidListService(searchKeyword.value);
    console.log('ID 查询结果:', result); // 打印查询结果，方便调试
    students.value = result.data ? (Array.isArray(result.data) ? result.data : [result.data]) : [];
   
}

// 声明异步函数，根据关键词查询学生信息
const searchStudent = async() => {
    if (!searchKeyword.value) {
        ElMessage.warning('请输入学生 ID 或姓名');
        return;
    }
    
    if (!isNaN(searchKeyword.value)) {
        // 输入是数字，调用 searchStudentById
        await searchStudentById();
    } else {
         // 输入是字符串，调用 studentshowbynameListService
        const result = await studentshowbynameListService(searchKeyword.value);
        console.log('姓名查询结果:', result); // 打印查询结果，方便调试
        students.value = result.data ? (Array.isArray(result.data) ? result.data : [result.data]) : [];
    }
    
}


//控制添加分类弹窗
const dialogVisible = ref(false)


//添加数据模型
const studentModel = ref({
    id: 0,
    name: '',
    age: 0,
    sex: '',
    grade: 1, 
    temp: 1   
})
//分类表单校验
const studentRules = {
    id:[
        { required: true, message: '请输入学号', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { type: 'number', min: 0, max: 150, message: '年龄范围在 0 - 150 之间', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '请输入性别', trigger: 'blur' },
    ],
}

//调用接口，添加表单
const addStudent = async() =>{
  
    //调用接口
    let result = await studentAddService(payload)
    ElMessage.success(result.msg?result.msg:'添加成功')
    //调用分类函数
    studentList();
    dialogVisible.value = false;

}

//定义变量，控制标题展示
const title = ref('')

//展示编辑弹窗
const showDialog = (row) =>{
    dialogVisible.value = true;
    title.value = '编辑学生';
    //数据拷贝
    studentModel.value.id = row.id;
    studentModel.value.name = row.name;
    studentModel.value.age = row.age;
    studentModel.value.sex = row.sex;
    studentModel.value.grade = row.grade;
    studentModel.value.temp = row.temp;
}

//编辑学生
const updateStudent = async() =>{

    //调用接口
    let result = await studentUpdateService(studentModel.value)
    
    ElMessage.success(result.msg?result.msg:'修改成功')
    //调用分类函数
    studentList();
    //隐藏弹窗
    dialogVisible.value = false;
}

//清空模型的数据
const clearData = () =>{
    studentModel.value = {
        id: 0, 
        name: '',
        age: 0,
        sex: '',
        grade: 1, 
        temp: 1
    };
}

//删除学生
const deleteStudent = async(row) =>{
    ElMessageBox.confirm(
        '你确认要删除信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(async() => {
        //调用接口
        let result =await studentDeleteService(row.id);
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
        //刷新列表
        studentList();
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
      })
    })
}



</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <div>
                    <el-input
                        v-model="searchKeyword"
                        placeholder="请输入学生 ID 或姓名"
                        style="width: 200px; margin-right: 10px;"
                    >
                        <template #append>
                            <el-button @click="searchStudent">查询</el-button>
                        </template>
                    </el-input>
                    <el-button @click="studentList">显示全部</el-button>
                </div>
                <div class="extra">
                    <el-button type="primary" @click="dialogVisible = true; title='添加学生'; clearData()">添加学生</el-button>
                </div>
            </div>
        </template>
        <el-table :data="students" style="width: 100%">
            <el-table-column label="序号" prop="id"> </el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="年龄" prop="age"></el-table-column>
            <el-table-column label="性别" prop="sex"></el-table-column>
            <el-table-column label="年级">
                <template #default="{ row }">
                    {{ row.grade === 1 ? '研一' : row.grade === 2 ? '研二' : row.grade === 3 ? '研三' : '未知' }}
                </template>
            </el-table-column>
            <el-table-column label="成绩">
                <template #default="{ row }">
                    {{ row.toscore ? row.toscore.toFixed(1) : '无' }}
                </template>
            </el-table-column>
            <!-- 奖项 -->
            <el-table-column label="奖项">
                <template #default="{ row }">
                    {{ row.temp === 1 ? '国奖' : row.temp === 2 ? '省奖' : row.temp === 3 ? '校奖' : '不获奖' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteStudent(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form :model="studentModel" :rules="studentRules" label-width="100px" style="padding-right: 30px">
                 <el-form-item label="学生编号" prop="id">
                    <el-input-number 
                        v-model="studentModel.id" 
                        :min="1" 
                        :precision="0" 
                        :step="1"
                        :max="9999999999"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="studentModel.name" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number 
                        v-model="studentModel.age" 
                        :min="0" 
                        :precision="0" 
                        :step="1"
                        :max="150"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-input v-model="studentModel.sex" minlength="1" maxlength="50"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="title == '添加学生'?addStudent() : updateStudent()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>
